import screenfull from 'screenfull'
import YSUtils from '../Utils'
import qs from 'qs'

const Utils = {
  colors: [
    'darkgray', 'green', 'red', 'yellow',
    'pink', 'orange', 'cyan', 'yellowgreen',
    'blue', 'purple', 'geekblue', 'magenta',
    'volcano', 'gold', 'lime'
  ],
  formatter: {
    status: (val, row, index, column, t) => {
      const h = t.$createElement
      const colors = Utils.colors
      column.customColors = Object.assign({}, colors, column.customColors || {})
      return h({
        render: () => {
          return (<a-badge color={column.customColors[val % Object.keys(column.customColors).length]} text={column.searchList[val] || val} />)
        }
      })
    },
    tag: (val, row, index, column, t) => {
      const h = t.$createElement
      const colors = Utils.colors
      column.customColors = Object.assign({}, colors, column.customColors || {})
      !column.searchList && (column.searchList = {})
      return h({
        render: () => {
          return (<div>{
            val.toString().split(',').map((item, index) => {
              return (<a-tag
                style="width:100%;text-align:center;overflow:hidden;white-space: nowrap;text-overflow: ellipsis;"
                color={column.customColors[item % Object.keys(column.customColors).length]}
                title={column.searchList[item] || item}>
                  {column.searchList[item] || item}
                </a-tag>)
            })
          }</div>)
        }
      })
    },
    image: (val, row, index, column, t) => {
      return YSUtils.image.call(t, val)
    },
    operate: (val, row, index, column, t) => {
      var buttons = []
      const actions = t.defaultConfig.extend.actions

      actions.detail && buttons.push({
        name: 'detail',
        url: '',
        icon: '',
        title: t.__('table.detail'),
        text: t.__('table.detail'),
        on: {
          click: (e) => Utils.events.detail(e, t, row)
        }
      })
      actions.edit && buttons.push({
        name: 'edit',
        url: '',
        icon: '',
        title: t.__('table.edit'),
        text: t.__('table.edit'),
        on: {
          click: (e) => Utils.events.edit(e, t, row)
        }
      })
      actions.delete && buttons.push({
        name: 'delete',
        url: '',
        icon: '',
        title: t.__('table.delete'),
        text: t.__('table.delete'),
        on: {
          click: (e) => {
            const p = {}
            const {
              rowKey
            } = t.defaultConfig
            p[rowKey] = row[rowKey]
            return Utils.events.delete(e, t, p)
          }
        }
      })
      column.buttons instanceof Array && column.buttons.map((button) => {
        if (button.events) {
          button.on || (button.on = {})
          Object.keys(button.events).forEach((eventType) => {
            button.on[eventType] = (e) => {
              return button.events[eventType](e, val, row, index, column, t)
            }
          })
        }
        buttons.push(button)
      })

      var btns = []
      if (typeof column.buttonHandle === 'function') {
        buttons.forEach((button) => {
          column.buttonHandle(button, row, index, column, t) && btns.push(button)
        })
      } else {
        btns = buttons
      }

      return Utils.formatter.buttons(btns, t)
    },
    buttons: (buttons, t) => {
      const h = t.$createElement
      return h({
        render: () => {
          return (<span>
              {
                ((buttons) => {
                  if (buttons.length === 0) {
                    return ''
                  } else if (buttons.length === 1) {
                    const on = buttons[0].on || {}
                    buttons[0].on && (delete buttons[0].on)
                    const props = buttons[0]
                    return (<a {...{ props, on }}>{buttons[0].text || buttons[0].title}</a>)
                  } else if (buttons.length === 2) {
                    return buttons.map((button, index) => {
                      const on = button.on || {}
                      button.on && (delete button.on)
                      const props = button
                      if (index === 0) {
                        return (<span><a {...{ props, on }}>{button.text || button.title}</a></span>)
                      } else {
                        return (<span><a-divider type="vertical" /><a {...{ props, on }}>{button.text || button.title}</a></span>)
                      }
                    })
                  } else {
                    var button = buttons.splice(0, 1)
                    const on = button[0].on || {}
                    button[0].on && (delete button[0].on)
                    const props = button[0]
                    return (<span>
                        <a {...{ props, on }}>{button[0].text || button[0].title}</a>
                        <a-divider type="vertical" />
                        <a-dropdown>
                          <a-menu slot="overlay">
                            {
                              buttons.map((button) => {
                                const on = button.on || {}
                                const props = button
                                return (<a-menu-item><a {...{ props, on }}>{button.text || button.title}</a></a-menu-item>)
                              })
                            }
                          </a-menu>
                          <a>{t.__('table.more')} <a-icon type="down"/></a>
                        </a-dropdown>
                      </span>)
                  }
                })(buttons)
              }
            </span>)
        }
      })
    },
    toolbars: {
      multi: (items, t) => {
        const h = t.$createElement
        return h({
          render: (h) => {
            return (<a-dropdown disabled={!t.defaultConfig.rowSelection || t.defaultConfig.rowSelection.selectedRowKeys.length <= 0}>
              <a-menu slot="overlay" onClick={({ key, keyPath, item, domEvent }) => { Utils.events.multi(domEvent, t, key) }}>
                { Object.keys(items).map((key) => {
                  return <a-menu-item key={key}>{items[key]}</a-menu-item>
                }) }
              </a-menu>
              <a-button> {t.__('批量操作')} <a-icon type="down" /> </a-button>
            </a-dropdown>)
          }
        })
      }
    }
  },
  events: {
    add: (e, t) => {
      Utils.dialog(t, (t.defaultConfig.extend.actions.add || (() => import('@/views/exception/build-page'))), {
        on: {
          ok (e) {
            t.$emit('refresh')
          },
          cancel (e) {}
        }
      }, {
        title: t.__('table.add')
      })
    },
    detail: (e, t, row) => {
      Utils.dialog(t, (t.defaultConfig.extend.actions.detail || (() => import('@/views/exception/build-page'))), row, {
        title: t.__('table.detail')
      })
    },
    edit: (e, t, row) => {
      Utils.dialog(t, (t.defaultConfig.extend.actions.edit || (() => import('@/views/exception/build-page'))), Object.assign({}, row, {
        on: {
          ok (e) {
            t.$emit('refresh')
          }
        }
      }), {
        title: t.__('table.edit')
      })
    },
    delete: (e, t, p) => {
      t.$confirm({
        title: '确定要删除吗?',
        okText: '确认',
        cancelText: '取消',
        onOk: () => {
          return t.defaultConfig.extend.actions.delete(p).then(() => {
            t.$notification['success']({
              message: '删除成功',
              duration: 4
            })
            t.$emit('refresh', true)
          })
        }
      })
    },
    multi: (e, t, key) => {
      const p = qs.parse(key)
      const {
        rowKey,
        rowSelection
      } = t.defaultConfig
      p[rowKey] = []
      rowSelection.selectedRows.forEach((item) => {
        p[rowKey].push(item[rowKey])
      })
      p[rowKey] = p[rowKey].join(',')
      t.$confirm({
        title: t.__('确定要操作吗?'),
        okText: t.__('确认'),
        cancelText: t.__('取消'),
        onOk: () => {
          return t.defaultConfig.extend.actions.multi(p).then(() => {
            t.$notification['success']({
              message: t.__('操作成功'),
              duration: 4
            })
            t.$emit('refresh', true)
          })
        }
      })
    },
    refresh: (e, t, bool) => {
      t.refresh(bool)
    },
    fullscreen: (e, t, Element) => {
      if (!screenfull.isEnabled) {
        t.$notification['error']({
          message: '不支持全屏',
          duration: 4
        })
        return false
      }
      screenfull.toggle(Element)
    },
    columnHeight: (e, t, size) => {
      t.defaultConfig.size = size
    }
  },
  dialog: YSUtils.dialog
}

export default Utils
